package com.mlnx.sim.ecg;

import com.mlnx.mptp.ResponseCode;
import com.mlnx.mptp.mptp.MpPacket;
import com.mlnx.sim.ecg.client.MpClientLis;
import com.mlnx.tp.base.utils.LogUtils;

/**
 * @author fzh
 * @create 2018/3/26 17:32
 */
public class MpService implements MpClientLis {

    private MpClient mpClient;

    private boolean isRegister = false;

    private String deviceId;

    private CallBack callBack;

    public MpService(CallBack callBack) {
        this.callBack = callBack;
        mpClient = new MpClient(this);
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    public void register() {
        mpClient.register(deviceId);
    }

    public boolean isRegister() {
        return isRegister;
    }

    public void push(MpPacket packet) {
        if (isRegister) {

            mpClient.push(packet);
//            LogUtils.i("发送push包:" + packet.getBody().getMessageId());
        } else {
            register();
        }
    }

    @Override
    public void receive(MpPacket mpPacket) {
        switch (mpPacket.getHeader().getPacketType()) {
            case Reg_ACK:
                if (mpPacket.getBody().getResponseCode().equals(ResponseCode.SUCESS)) {
                    isRegister = true;
                    LogUtils.i("注册成功");
                }
                break;
            case PINGREQ:
                mpClient.pong();
                LogUtils.i("响应pong包");
                break;
            case PINGRESP:
                LogUtils.d("收到pong包");
                break;
            case PUBLISH:

                break;
            case PUBLISH_ACK:
//                LogUtils.d("收到推送回复:" + mpPacket.getBody().getResponseCode() + "  " + mpPacket.getBody().getMessageId());

                if (mpPacket.getBody().getResponseCode().equals(ResponseCode.NOT_REGISTER)) {
                    isRegister = false;
                } else if (mpPacket.getBody().getResponseCode().equals(ResponseCode.SUCESS)) {
                    callBack.pushAck(mpPacket.getBody().getMessageId());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void sendError() {
        mpClient.disConnect();
    }

    @Override
    public void close() {
        isRegister = false;
    }

    public interface CallBack {
        void pushAck(Integer messageId);
    }
}
